﻿using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using builderDesignMode.Configuration.Provider;

namespace builderDesignMode.Configuration
{
    public class ConfigurationBuilder
    {
        public Configuration configuration { get; set; }

        /// <summary>
        /// 建造者模式 创建 Configuration对象
        /// </summary>
        public ConfigurationBuilder()
        {

        }

        /// <summary>
        /// 建造者模式 遵守开闭原则 拆分出来
        /// </summary>
        /// <param name="jsonFilePath"></param>
        /// <param name="optional"></param>
        /// <param name="onRealodChange"></param>
        /// <returns></returns>
        public ConfigurationBuilder AddJsonFile(string jsonFilePath, bool optional, bool onRealodChange)
        {
            FileConfigurationSourcex fileConfigurationSource = new FileConfigurationSourcex()
            {
                jsonFilePath = jsonFilePath,
                optional = optional,
                onRealodChange = onRealodChange
            };
            JsonConfigurationProvider jsonConfigurationProvider = new JsonConfigurationProvider();
            jsonConfigurationProvider.jsonConfigurationSource = fileConfigurationSource;
            jsonConfigurationProvider.AddJsonConfigurationFile();

            configuration.configurationProviders.Add(jsonConfigurationProvider);    
            return this;
        }

        /// <summary>
        /// 建造者模式 遵守开闭原则 拆分出来
        /// </summary>
        /// <param name="xmlFilePath"></param>
        /// <returns></returns>
        public ConfigurationBuilder AddXmlFile(string xmlFilePath)
        {
            // 1、读取xml文件
            using (StreamReader file = File.OpenText(xmlFilePath))
            {
                // 2、解析xml文件
                using (JsonTextReader reader = new JsonTextReader(file))
                {
                    JObject jObject = (JObject)JToken.ReadFrom(reader);
                    var value = jObject["AllowedHosts"].ToString();

                    // 3、设值到Data
                    XmlConfigurationProvider xmlConfigurationProvider = new XmlConfigurationProvider();

                    xmlConfigurationProvider.keyValuePairs.Add("AllowedHosts", value);

                    configuration.configurationProviders.Add(xmlConfigurationProvider);
                }
            }
            return this;
        }

        /// <summary>
        /// 构建对象
        /// </summary>
        /// <returns></returns>
        public Configuration Builder()
        {
            return configuration;
        }
    }
}
